<template>
	<view class="chat">

		<scroll-view :style="{height: `${windowHeight-inputHeight }rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in messageList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self">
						<!-- 文字内容 -->
						<view class="content right" v-if="!item.imgs">
							{{item.content}}
						</view>
						<view class=" right-image" v-else>
							<image class="image-right" :src="item.imgs[0]"  @click="showBig(item.imgs[0])"></image>
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="image">
						</image>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-for="(reply,index1) in item.replyList" v-if="item.replyList">
						<!-- 头像 -->
						<image class="avatar" src="/static/images/mall/my/mine_def_touxiang_3x.png">
						</image>
						<!-- 文字内容 -->
						<view class="content left" v-if="!reply.imgs">
							{{reply.content}}
						</view>
						<view class=" left-image" v-else>
							<image v-for="(img,index2) in reply.imgs" :key="index2" class="image-left" :src="img" @click="showBig(img)"></image>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="action-box">
			<view class="action-top">
				<!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
				<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
					<view class="send-msg" :style="{bottom:`${keyboardHeight - 60}rpx`}">
						<view class="uni-textarea">
							<textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend(false)"
								placeholder="快来聊天吧~" :show-confirm-bar="false" :adjust-position="false"
								@linechange="sendHeight" @focus="focus" @blur="blur" auto-height></textarea>
						</view>
						<button @click="handleSend(false)" class="send-btn">发送</button>

						<image @click="showOtherTypesMessagePanel()" class="more-right"
							src="/static/images/chat/more.png" />
					</view>
				</view>
			</view>

			<!--其他类型消息面板-->
			<view v-if="otherTypesMessagePanelVisible" class="action-bottom">
				<view class="more-icon">
					<image @click="chooseImages()" class="operation-icon" src="/static/images/chat/picture.png">
					</image>
					<view class="operation-title">图片</view>
				</view>
				<!-- 	<view class="more-icon">
					<image @click="sendVideoMessage()" class="operation-icon" src="/static/images/chat/video.png">
					</image>
					<view class="operation-title">视频</view>
				</view>
				<view class="more-icon">
					<image @click="redHand()" class="operation-icon" src="/static/images/chat/red.png">
					</image>
					<view class="operation-title">红包</view>
				</view> -->
			</view>
		</view>


	</view>
</template>
<script>
	export default {
		data() {
			return {
				//是否展示‘其他消息类型面板’
				otherTypesMessagePanelVisible: false,
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId: '',
				//发送的消息
				chatMsg: "",
				msgList: [{
						botContent: "你好啊，很高兴你可以关注我，请问我有什么可以帮助你的吗？",
						userContent: "",
						image: ""
					},
					{
						botContent: "",
						userContent: "你好呀，非常高兴认识你",
						image: ""
					},
				],
				image: '',
				pageIndex: 1,
				messageList: '',
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();

		},
		
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight -40
			}
		},
		onLoad() {
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			})
			this.image = this.tui.getUserInfoData().user_headimg
			this.getList()
		},
		onUnload() {
			// uni.offKeyboardHeightChange()
		},
		methods: {

			getList() {

				let token = this.tui.getToken();
				let datas = {
					page: this.pageIndex,
					limit: 10000
				};
				let products = this.tui.request('Message', 'post', datas, 1000, 1, '', 'messageList');
				Promise.resolve(products).then((value) => {

					if (value.code == 200) {
						if (value.data.data) {
							this.messageList = value.data.data;
						}
					}
				})

			},
			showBig(url) {
				uni.previewImage({
					urls: [url],
					current: url
				})
			},
			showOtherTypesMessagePanel() {
				this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
				this.scrolltoBottoms();
			},
			scrolltoBottoms() { //console.log('scrolltoBottom',this.autodown,is_real)

				this.$nextTick(() => {
					this.timer = setTimeout(() => {
						uni.pageScrollTo({
							scrollTop: 9999999,
							duration: 10
						});
					}, 200);
				});

			},
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			// 发送消息
			handleSend(image) {
				//如果消息不为空
				let token = this.tui.getToken();
				let datas = {}
				if (image) {
					datas = {
						content: this.chatMsg,
						imgs: image
					};
				} else {
					datas = {
						content: this.chatMsg,

					};
				}

				let products = this.tui.request('Message', 'post', datas, 1000, 1, '', 'postAMessage');
				Promise.resolve(products).then((value) => {

					if (value.code == 200) {
						if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
							let arr = []
							arr.content = this.chatMsg
							this.messageList.push(arr)
							// this.msgList.push(obj);
							this.chatMsg = '';
							this.scrollToBottom()
						} else {
							this.$modal.showToast('不能发送空白消息')
						}
					}
				})

			},
			//上传图片
			chooseImages: async function() {
				uni.chooseImage({
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					count: 1,
					success: (res) => {
						console.log(res)
						let max_size = 5 * 1024 * 1024;
						// #ifdef H5
						if (res.tempFiles[0].type.indexOf("image") < 0) {
							this.tui.toast("请选择图片类型的文件");
							return;
						}
						// #endif

						if (res.tempFiles[0].size >= max_size) {
							this.tui.toast("上传图片不能超过5M");
							return;
						}
						let token = this.tui.getToken();
						let name = res.tempFilePaths[0]
						let datas = {
							token: token,
							image: res.tempFiles[0]
						};
						let uper = this.tui.uploadFileVoucher('Message', datas, res.tempFilePaths[0],
							'upload', 'image');
						Promise.resolve(uper).then((value) => {
							uni.showToast({
								title: value.message,
								icon: 'none',
								duration: 2000
							})

							this.handleSend(value.data.image)
						})


					},
					fail: (err) => {
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						// #endif
					}
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import url('/static/css/chatInterface.css');
	@import "@/static/css/style.scss";
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
		.topTabbar {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			display: flex;
			// margin-top: 80rpx;
			justify-content: space-between;

			.icon {
				margin-left: 20rpx;
			}

			.text {
				margin: auto;
				font-size: 16px;
				font-weight: 700;
			}

			.button {
				width: 10%;
				margin: auto 20rpx auto 0rpx;
			}
		}

		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				// padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.right-image {
						background-color: transparent;
					}

					.left {
						background-color: #FFFFFF;
					}

					.left-image {
						background-color: transparent;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.image-right {
						width: 120rpx;
						height: 120rpx;
						margin: 0 24rpx;
					}

					.image-left {
						width: 120rpx;
						height: 120rpx;
						margin: 0 24rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;

						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				// background: #fff;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				padding-bottom: 70rpx;

				textarea {
					width: 507rpx;
					height: auto;
					min-height: 25rpx;
					max-height: 500rpx;
					background: #fff;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
					text-indent: 30rpx;
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 86rpx;
				margin-left: 15rpx;
				width: 90rpx;
				height: 55rpx;
				background: #ed5a65;
				border-radius: 45rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}

			.more-right {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 86rpx;
				margin-left: 15rpx;
				width: 55rpx;
				height: 55rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}

	}
</style>